package com.searchpopulistdemo;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements TextWatcher {


    @Bind(R.id.et_input)
    EditText mEtInput;
    @Bind(R.id.btn_commit)
    Button mBtnCommit;
    private ArrayList<String> mCountries;
    private ListPopupWindow mListPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        bindEvent();
        initView();
    }

    private void initView() {
        List<String> list = new ArrayList<>();
        list.add("abc");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("b");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");
        list.add("ccc");

        mListPopupWindow = new ListPopupWindow(this);
        mListPopupWindow.setAnchorView(mEtInput);
        SuggestArrayAdapter suggestArrayAdapter = new SuggestArrayAdapter(list,this);
        mListPopupWindow.setAdapter(suggestArrayAdapter);
        mListPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mListPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        mListPopupWindow.setModal(true);

//        mListPopupWindow.show();

    }


    private class SuggestArrayAdapter extends BaseAdapter{
        List<String> mList = new ArrayList<>();
        Context mContext;

        public SuggestArrayAdapter(List<String> list, Context context) {
            mList = list;
            mContext = context;
        }

        @Override
        public int getCount() {
            return mList.size();
        }
        @Override
        public Object getItem(int i) {
            return mList.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder = null;
            if (view==null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.item_tip, null);
                holder = new Holder(view);
                view.setTag(holder);
            }else {
                holder = (Holder) view.getTag();
            }
            holder.mTextView.setText(mList.get(i));
            return view;
        }
    }

    class Holder{
        TextView mTextView;

        public Holder(View view){
            mTextView = view.findViewById(R.id.tv_tip);
        }

    }


    private void bindEvent() {
        mEtInput.addTextChangedListener(this);
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.KITKAT) {
            mListPopupWindow.setDropDownGravity(Gravity.START);
        }
        mListPopupWindow.setAnchorView(mEtInput);
        mListPopupWindow.show();
    }


    private void loadSearch() {
        ArrayList<String> countryStored = new ArrayList<>();
        View view = getLayoutInflater().inflate(R.layout.view_toolbar_search, null);
        LinearLayout parentToolbarSearch = (LinearLayout) view.findViewById(R.id.parent_toolbar_search);
        ImageView imgToolBack = (ImageView) view.findViewById(R.id.img_tool_back);
        final EditText edtToolSearch = (EditText) view.findViewById(R.id.edt_tool_search);
        final ImageView imgCha = (ImageView) view.findViewById(R.id.img_cha1);
        TextView tvSearch = (TextView) view.findViewById(R.id.tv_tool_search);
        final ListView listSearch = (ListView) view.findViewById(R.id.list_search);
        final TextView txtEmpty = (TextView) view.findViewById(R.id.txt_empty);

        SearchUtils.setListViewHeightBasedOnChildren(listSearch);
        edtToolSearch.setHint("告警 工单 站点 用户");
        final Dialog toolbarSearchDialog = new Dialog(this, R.style.MaterialSearch);



        toolbarSearchDialog.setContentView(view);
        toolbarSearchDialog.setCancelable(false);
        toolbarSearchDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        toolbarSearchDialog.getWindow().setGravity(Gravity.BOTTOM);


        toolbarSearchDialog.show();
        toolbarSearchDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        countryStored = (countryStored != null && countryStored.size() > 0) ? countryStored : new ArrayList<String>();
        final SearchAdapter searchAdapter = new SearchAdapter(this, countryStored, false);
        listSearch.setVisibility(View.VISIBLE);
        listSearch.setAdapter(searchAdapter);

        listSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                String country = String.valueOf(adapterView.getItemAtPosition(position));
                SharedPreference.addList(MainActivity.this, SearchUtils.PREFS_NAME, SearchUtils.KEY_COUNTRIES, country);
                edtToolSearch.setText(country);
                listSearch.setVisibility(View.GONE);
            }
        });
        edtToolSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String[] country = MainActivity.this.getResources().getStringArray(R.array.countries_array);
                mCountries = new ArrayList<String>(Arrays.asList(country));
                listSearch.setVisibility(View.VISIBLE);
                searchAdapter.updateList(mCountries, true);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ArrayList<String> filterList = new ArrayList<String>();
                boolean isNodata = false;
                if (s.length() > 0) {
                    for (int i = 0; i < mCountries.size(); i++) {
                        if (mCountries.get(i).toLowerCase().startsWith(s.toString().trim().toLowerCase())) {
                            filterList.add(mCountries.get(i));
                            listSearch.setVisibility(View.VISIBLE);
                            searchAdapter.updateList(filterList, true);
                            isNodata = true;
                        }
                    }
                    if (!isNodata) {
                        listSearch.setVisibility(View.GONE);
                        txtEmpty.setVisibility(View.VISIBLE);
                        txtEmpty.setText("没有数据");
                    }
                } else {
                    listSearch.setVisibility(View.GONE);
                    txtEmpty.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(edtToolSearch.getText().toString().trim())) {
                    imgCha.setVisibility(View.GONE);
                } else {
                    imgCha.setVisibility(View.VISIBLE);
                }
            }
        });

        imgToolBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toolbarSearchDialog.dismiss();
            }
        });

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edtToolSearch.getText().toString().trim())) {
                    return;
                }
                //commit
            }
        });
        imgCha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtToolSearch.setText("");
            }
        });
    }

    @OnClick({ R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_commit:
                loadSearch();
                break;
        }
    }
}
